package com.wsx.sky.http;

import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.DefaultConnectionKeepAliveStrategy;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author wangshuaixin
 * @Title: com.wsx.sky.http.HttpPool
 * @Description: TODO
 * @date 2018/12/10
 */
@Configuration
public class HttpPool {

    @Bean
    public HttpClient httpClient() {

        RequestConfig.Builder builder = RequestConfig.custom();
        //超时时间
        builder.setSocketTimeout(2 * 1000);
        //连接超时时间
        builder.setConnectTimeout(500);

        RequestConfig config = builder.build();

        //连接池的配置
        //长连接保持30秒
        final PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager();
        //连接池的总连接数
        manager.setMaxTotal(500);
        //相同路由的并发数
        manager.setDefaultMaxPerRoute(100);

        HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
        //长连接需要在header上增加keep-alive
        httpClientBuilder.setKeepAliveStrategy(new DefaultConnectionKeepAliveStrategy());
        httpClientBuilder.setConnectionManager(manager);
        httpClientBuilder.setDefaultRequestConfig(config);

        HttpClient httpClient = httpClientBuilder.build();

        return httpClient;
    }
}
